const basicAuth = require('basic-auth');
const jwt = require('jsonwebtoken')

/**
 * @token权限认证层
 */
class Auth {
    constructor(level){ //level是某个接口所需的权限等级
        this.level = level || 1
        Auth.USER = 8 // 普通用户
        Auth.ADMIN = 16 // 管理员
        Auth.SUPER = 32 // 超级管理员
    }
    static verifyToken(token){
        try {
            jwt.verify(token,global.config.security.secretKey)
            return true
        } catch (error) {
            return false
        }
    }
    get m(){
        return async (ctx,next)=>{
            //token检测
            //token 开发者 传递令牌
            // token body header 约定
            const token = basicAuth(ctx.req);
            let errMsg = 'token不合法'
            if(!token || !token.name){
                throw new global.errs.Forbbiden([errMsg])
            }
            try {
                var decode = jwt.verify(token.name,global.config.security.secretKey)
            }catch(error){
                if(error.name == 'TokenExpiredError'){
                    throw new global.errs.Forbbiden(['登陆已过期'])
                }
                throw new global.errs.Forbbiden([errMsg])
            }

            if(decode.scope < this.level){
                errMsg = '权限不足'
                throw new global.errs.Forbbiden([errMsg])
            }

            ctx.auth = {
                uid:decode.uid,
                scope:decode.scope
            }

            await next()
        }
    }
}

module.exports = { Auth }